package storage

import (
	"fmt"

	"github.com/toolkits/pkg/errorx"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

var (
	DB  *gorm.DB
	err error
)

type DBConfig struct {
	Host          string
	Port          int
	Username      string
	Password      string
	DBName        string
	SingularTable bool
}

func InitDB(conf DBConfig) {
	DB, err = gorm.Open(mysql.Open(fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		conf.Username,
		conf.Password,
		conf.Host,
		conf.Port,
		conf.DBName)),
		&gorm.Config{
			NamingStrategy: schema.NamingStrategy{
				SingularTable: conf.SingularTable, // 使用单数表名，启用该选项后，`User` 表将是`user`
			},
		},
	)
	if err != nil {
		errorx.Bomb(1, err.Error())
	}
}
